package com.woniuxy.juc.reentrant;

import com.woniuxy.untis.Sleep;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 锁超时 避免线程无限制等待锁 如果超时 则不会等待
 * <P> Date: 2022/4/8:8:54
 * <P> Description:
 */
@Slf4j(topic = "c.ReentrantLockTest3")
public class ReentrantLockTest3 {
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            //TODO 获取失败
            log.debug("尝试获取锁");
            try {
                if (!lock.tryLock(1, TimeUnit.SECONDS)) {
                    log.debug("没有获取锁");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("没有获取锁");
                return;
            }
            try {
                log.debug("获取到锁");
            } finally {
                lock.unlock();
            }
        }, "t1");

        lock.lock();

        try {
            log.debug("获取到锁");
            t1.start();
        }finally {
            lock.unlock();
        }

    }
}
